package com.sea.supply.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.physical.service.CreatePlanService;
import com.sea.supply.entity.Produce;
import com.sea.supply.entity.ProducePayment;
import com.sea.supply.entity.Receive;
import com.sea.supply.service.ProducePaymentService;
import com.sea.supply.service.ProduceService;
import com.sea.supply.service.SupplierService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/supply/produce/payment")
public class ProducePaymentController {

    @Autowired
    private ProduceService produceService;
    @Autowired
    private ProducePaymentService producePaymentService;
    @Autowired
    private CreatePlanService createPlanService;

    public static void main(String[] args) {
        try {
            // 加载PDF文件
            File pdfFile = new File("F://package-FBA18TKK8YL8.pdf"); // 替换为您的PDF文件路径
            PDDocument document = PDDocument.load(pdfFile);

            // 使用PDFTextStripper提取文本
            PDFTextStripper pdfStripper = new PDFTextStripper();

            // 设置只提取第一页
            pdfStripper.setStartPage(1);
            pdfStripper.setEndPage(1);

            // 提取文本
            String pageText = pdfStripper.getText(document);

            // 输出第一页的文本内容
            System.out.println("第一页的文本内容:");
            System.out.println(pageText);

            // 关闭文档
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {

        return "/sea/supply/producePayment/main";
    }

    @RequestMapping("/addPage")
    public String addPage(Model model,@RequestParam("produceId")Integer produceId) {
        model.addAttribute("produceId",produceId);
        model.addAttribute("refusedPo",createPlanService.findPaymentCreatePlanNo());
        return "/sea/supply/producePayment/add";
    }

    /**
     * 修改页面
     * @param model
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model,@RequestParam("id")Integer id) {
        model.addAttribute("payment",producePaymentService.findById(id));
        return "/sea/supply/producePayment/edit";
    }



    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Produce produce) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Produce> list = produceService.findByPayment(produce);
        PageInfo<Produce> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 新增
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxReturn delete(Integer id) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null != id && producePaymentService.delete(id) > 0) {
                result.setOk(true).setMsg("删除成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 分页条件查询
     *
     * @param produceId
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByProduceId")
    public List<ProducePayment> findByProduceId(Integer produceId) {
        return producePaymentService.findByProduceId(produceId);
    }
    /**
     * 新增
     * @param producePayment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(ProducePayment producePayment) {
        AjaxReturn result = Ajax.fail().setMsg("新增失败！");
        try{
            if (null != producePayment && producePaymentService.save(producePayment) > 0) {
                result.setOk(true).setMsg("新增成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importDetail(Model model,
                                MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                InputStream is = file.getInputStream();
                producePaymentService.importPayment(is,fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 新增
     * @param producePayment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(ProducePayment producePayment) {
        AjaxReturn result = Ajax.fail().setMsg("新增失败！");
        try{
            if (null != producePayment && producePaymentService.usave(producePayment) > 0) {
                result.setOk(true).setMsg("新增成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    /**
     * 导出待收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void exportShipped(HttpServletRequest request, HttpServletResponse response, Produce produce) {
        List<Produce> list=produceService.findByPayment(produce);
        String[] title = {"采购单号","供应商","采购总量","实收数量","实收金额","采购总价","预付款","待核销", "已申请金额","未申请金额","已付款金额","备注","付款异常","创建时间"};
        String fileName = "付款记录表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "付款记录表";
        String[][] content = new String[list.size()][14];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Produce obj = list.get(i);
            content[i][0] = obj.getProduceNo();
            content[i][1] = obj.getProduceSupplierName();
            content[i][2] = obj.getProduceTotal()+"";
            content[i][3] = (obj.getProduceTotal()-obj.getProduceSurplus())+"";
            content[i][4] = obj.getProduceAlreadyPay()+"";
            content[i][5] = obj.getProduceTotalMoney()+"";
            content[i][6] = obj.getProducePayment()+"";
            content[i][7] = obj.getProduceWaitPay()+"";
            content[i][8] = obj.getProducePay()+"";
            content[i][9] =(obj.getProduceAlreadyPay()-(null==obj.getProducePay()?0:obj.getProducePay()))+"";
            content[i][10] = obj.getProducePayMoney()+"";
            content[i][11] = obj.getProducePaymentRemark();
            Integer status = obj.getProducePaymentStatus();
            if(null != status && status==1) {
                content[i][12] ="无异常";
            }else{
                content[i][12] ="";
            }
            content[i][13] = obj.getCreateTime().substring(0,10);

        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
